package com.wang.example.heart;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

public class HeartbeatClientInHandler extends ChannelInboundHandlerAdapter {
    /**
     * 客户端读取到数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        ByteBuf bufMsg = (ByteBuf) msg;
        System.out.println("client receive:" + bufMsg.toString(CharsetUtil.UTF_8));
        //释放与池化的 ByteBuf 实例相关的内存
        ReferenceCountUtil.release(msg);
    }
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("client userEventTriggered");
        // send heartbeat when read idle.
        if (evt instanceof IdleStateEvent) { //如果在规定的事件没有
            try {
//                ByteBuf resBuf = Unpooled.copiedBuffer("heartbeat",
//                        CharsetUtil.UTF_8);
//                ctx.channel().writeAndFlush(resBuf);
            } finally {
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
